package com.melichercik.code;

import java.util.ArrayList;

import android.graphics.Canvas;

public class CodePainter {
	
	private Canvas canvas;
	private ArrayList<Brick> code = new ArrayList<Brick>();
	
	private int offsetX;
	private int offsetY;
	private int scale;
	private int loopDepth = 0;
	
	public CodePainter(Canvas canvas, ArrayList<Brick> code, int offsetX, int offsetY, int scale) {
		this.canvas = canvas;
		this.code = code;
		this.offsetX = offsetX;
		this.offsetY = offsetY;
		this.scale = scale;
	}
	
	public void renderCode() {
		canvas.drawARGB(255, 255, 255, 255);
		
		for(Brick brick: code) {
			renderBrick(brick);
		}
	}
	
	private void renderBrick(Brick brick) {
		String[] loopCounter = {"X", "Y", "Z"};
		String brickType = brick.getType();
		
		if (brickType == Brick.START 
			|| brickType == Brick.END 
			|| brickType == Brick.ROLL 
			|| brickType == Brick.STOP 
			|| brickType == Brick.PRINT
			|| brickType == Brick.SOUND
			|| brickType == Brick.COLOR
			|| brickType == Brick.LED
			|| brickType == Brick.DELAY
			|| brickType == Brick.ENDLOOP
			|| brickType == Brick.ENDWHILE
			|| brickType == Brick.VARIABLE
		) {
			SimpleBrick tmpBrick = ((SimpleBrick) brick);
			tmpBrick.render(canvas, offsetX, offsetY, scale);
			if (brickType == Brick.ENDLOOP) {
				loopDepth--;
			}
			
		} else if (brickType == Brick.LOOP || brickType == Brick.WHILE) {
			LoopBrick tmpBrick = ((LoopBrick) brick);
			tmpBrick.counter = loopCounter[loopDepth];
			tmpBrick.render(canvas, offsetX, offsetY, scale);
			if (brickType == Brick.LOOP) {
				loopDepth++;
			}
		
		} else if (brickType == Brick.IF) {
			IfBrick tmpBrick = ((IfBrick) brick);
			tmpBrick.render(canvas, offsetX, offsetY, scale);
			
		} else if (brickType == Brick.THEN
			|| brickType == Brick.ENDTHEN
			|| brickType == Brick.ELSE
			|| brickType == Brick.ENDELSE
			|| brickType == Brick.ENDIF
		) {
			HelperBrick tmpBrick = ((HelperBrick) brick);
			tmpBrick.render(canvas, offsetX, offsetY, scale);
		}
	}
}
